package com.tanhua.admin.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.mapper.AnalysisMapper;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.model.domain.Analysis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class AnalysisService {
    @Autowired(required = false)
    private AnalysisMapper analysisMapper;

    @Autowired(required = false)
    private LogMapper logMapper;

    public void analyseByDay() {
        String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        //查询每日注册人数
        Integer numRegistered = logMapper.queryByTypeAndLogTime("0102", today);

        //查询每日活跃人数
        Integer numActive = logMapper.queryByLogTime(today);

        //查询每日登录次数
        Integer numLogin = logMapper.queryNumLogin("0101", today);

        //查询每日次日保留人数
        String yesterday = DateUtil.yesterday().toString("yyyy-MM-dd");
        Integer numRetention1d = logMapper.queryNumRetention1d(today, yesterday);

        QueryWrapper<Analysis> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("record_date", today);
        Analysis analysis = analysisMapper.selectOne(queryWrapper);

        if (analysis == null) {
            analysis = new Analysis();
            analysis.setRecordDate(new Date());
            analysis.setNumRegistered(numRegistered);
            analysis.setNumActive(numActive);
            analysis.setNumLogin(numLogin);
            analysis.setNumRetention1d(numRetention1d);
            analysis.setCreated(new Date());
            analysis.setUpdated(new Date());
            analysisMapper.insert(analysis);
        } else {
            analysis.setNumRegistered(numRegistered);
            analysis.setNumActive(numActive);
            analysis.setNumLogin(numLogin);
            analysis.setNumRetention1d(numRetention1d);
            analysis.setUpdated(new Date());
            analysisMapper.updateById(analysis);
        }

    }

}
